<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="userQuery.name" placeholder="用户名" />
      </el-form-item>

      <el-form-item>
        <el-date-picker
          v-model="userQuery.begin"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="userQuery.end"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="getList()">查询</el-button>
      <el-button type="default" @click="resetData()">清空</el-button>
      <el-button type="default" @click="showUploadDialog()">上传</el-button>
      <a
        href="https://hbisedm-oss.oss-cn-hangzhou.aliyuncs.com/excel/Template01.xlsx"
        class="el-button"
      >
        下载模板</a
      >
    </el-form>

    <!-- 表格 -->
    <el-table :data="list" border fit highlight-current-row>
      <el-table-column label="ID号  " width="70" align="center">
        <template slot-scope="scope">
          <!-- {{ (page - 1) * limit + scope.$index + 1 }} -->
          {{ scope.row.id }}
        </template>
      </el-table-column>

      <el-table-column prop="username" label="工号" width="100" />
      <el-table-column prop="othername" label="用户名" width="100" />

      <el-table-column prop="sex" label="性别" width="60">
        <template slot-scope="scope">
          {{ scope.row.sex == 1 ? "男" : "女" }}
        </template>
      </el-table-column>

      <el-table-column label="用户类型" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 0">管理员</el-tag>
          <el-tag v-else-if="scope.row.type == 1" type="success">学生</el-tag>
          <el-tag v-else-if="scope.row.type == 2" type="info">教师</el-tag>
          <el-tag v-else-if="scope.row.type === 3" type="warning">实习单位</el-tag>
          <!-- {{ scope.row.type==0?'管理员':'首席讲师' }} -->
        </template>
      </el-table-column>

      <el-table-column prop="email" label="邮箱" width="180" />

      <el-table-column prop="mobilephone" label="手机" width="160" />

      <el-table-column prop="department" label="系别" width="160" />

      <!-- <el-table-column prop="grade" label="班级" width="160" >
        <template slot-scope="scope">
          {{scope.row.grade}}班
        </template>
      </el-table-column> -->

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <router-link :to="'/teacher/edit/' + scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit">修改</el-button>
          </router-link>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deleteTeachByTid(scope.row.id)"
            >删除</el-button
          >
          <el-button type="warning" size="mini" plain @click="getNoTeachStuList(scope.row.id)"
            >添加学生</el-button
          >

          <el-button type="success" size="mini" plain @click="getStuList(scope.row.id)"
            >管理学生</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="对应管理学生列表" :visible.sync="hasTeachStatus">
      <el-table :data="stuList">
        <el-table-column property="othername" label="姓名" width="200"></el-table-column>
        <el-table-column property="department" width="200" label="系别"></el-table-column>
        <el-table-column property="grade" width="200" label="班级"></el-table-column>

        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteStu(scope.row.id)"
              >移除</el-button
            >
          </template></el-table-column
        >
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center"
        layout="total, prev, pager, next, jumper"
        @current-change="getList"
      />
    </el-dialog>

    <el-dialog title="学生列表" :visible.sync="dialogTableVisible">
      <el-table :data="stuList">
        <el-table-column property="othername" label="姓名" width="200"></el-table-column>
        <el-table-column property="department" width="200" label="系别"></el-table-column>
        <el-table-column property="grade" width="200" label="班级"></el-table-column>

        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-check"
              @click="addStu(scope.row.id)"
              >添加</el-button
            >
          </template></el-table-column
        >
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="stuPage"
        :page-size="limit"
        :total="stuTotal"
        style="padding: 30px 0; text-align: center"
        layout="total, prev, pager, next, jumper"
        @current-change="getNoTeachStuList()"
      />
    </el-dialog>

    <el-dialog
      title="上传教师Excel"
      :visible.sync="dialogAddFile"
      width="500px"
      style="padding: 0"
      @close="resetAdd"
    >
      <div
        class="add-file-right"
        style="height: 70px; margin-left: 100px; margin-top: 15px"
      >
        <div class="add-file-right-img" style="margin-left: 70px">上传文件：</div>
        <input
          type="file"
          ref="clearFile"
          @change="getFile($event)"
          multiple="multiplt"
          class="add-file-right-input"
          style="margin-left: 70px"
          accept=".xlsx"
        />
        <span class="add-file-right-more">支持扩展名：.xlsx </span>
      </div>
      <div class="add-file-list">
        <ul>
          <li v-for="(item, index) in addArr" :key="index">
            <a>{{ item.name }}</a>
          </li>
        </ul>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddFile" size="small">开始上传</el-button>
        <el-button @click="resetAdd" size="small">全部删除</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />

    <!-- <div id="main" style="width: 100%; height: 600px"></div> -->
  </div>
</template>

<script>
import teachApi from "@/api/teach";
import stuApi from "@/api/student";
import { mapGetters } from "vuex";

export default {
  computed: {
    ...mapGetters(["name", "roles"]),
  },
  data() {
    return {
      list: null,
      stuPage: 1,
      page: 1, //当前页
      limit: 10, //每页记录数
      total: 0, //总记录数
      userQuery: {}, //条件封装对象
      //学生列表
      stuList: null,
      stuTotal: 0,
      hasTeachStatus: false,
      dialogTableVisible: false,
      addFileName: "",
      dialogAddFile: false,
      addArr: [],
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.drawChart();
  },
  methods: {
    drawChart() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("main"));
      // 指定图表的配置项和数据
      var option = {
        title: {
          text: "折线图",
          subtext: "模拟数据",
          x: "center",
        },

        legend: {
          // orient 设置布局方式，默认水平布局，可选值：'horizontal'（水平） ¦ 'vertical'（垂直）
          orient: "horizontal",
          // x 设置水平安放位置，默认全图居中，可选值：'center' ¦ 'left' ¦ 'right' ¦ {number}（x坐标，单位px）
          x: "left",
          // y 设置垂直安放位置，默认全图顶端，可选值：'top' ¦ 'bottom' ¦ 'center' ¦ {number}（y坐标，单位px）
          y: "top",
          data: ["预期", "实际", "假设"],
        },

        //  图表距边框的距离,可选值：'百分比'¦ {number}（单位px）
        grid: {
          top: "16%", // 等价于 y: '16%'
          left: "3%",
          right: "8%",
          bottom: "3%",
          containLabel: true,
        },

        // 提示框
        tooltip: {
          trigger: "axis",
        },

        //工具框，可以选择
        toolbox: {
          feature: {
            saveAsImage: {}, //下载工具
          },
        },

        xAxis: {
          name: "周几",
          type: "category",
          axisLine: {
            lineStyle: {
              // 设置x轴颜色
              color: "#912CEE",
            },
          },
          // 设置X轴数据旋转倾斜
          axisLabel: {
            rotate: 30, // 旋转角度
            interval: 0, //设置X轴数据间隔几个显示一个，为0表示都显示
          },
          // boundaryGap值为false的时候，折线第一个点在y轴上
          boundaryGap: false,
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },

        yAxis: {
          name: "数值",
          type: "value",
          min: 0, // 设置y轴刻度的最小值
          max: 1800, // 设置y轴刻度的最大值
          splitNumber: 9, // 设置y轴刻度间隔个数
          axisLine: {
            lineStyle: {
              // 设置y轴颜色
              color: "#87CEFA",
            },
          },
        },

        series: [
          {
            name: "预期",
            data: [820, 932, 301, 1434, 1290, 1330, 1320],
            type: "line",
            // 设置小圆点消失
            // 注意：设置symbol: 'none'以后，拐点不存在了，设置拐点上显示数值无效
            symbol: "none",
            // 设置折线弧度，取值：0-1之间
            smooth: 0.5,
          },
          {
            name: "实际",
            data: [620, 732, 941, 834, 1690, 1030, 920],
            type: "line",
            // 设置折线上圆点大小
            symbolSize: 8,
            itemStyle: {
              normal: {
                // 拐点上显示数值
                label: {
                  show: true,
                },
                borderColor: "red", // 拐点边框颜色
                lineStyle: {
                  width: 5, // 设置线宽
                  type: "dotted", //'dotted'虚线 'solid'实线
                },
              },
            },
          },
        ],

        color: ["#00EE00", "#FF9F7F", "#FFD700"],
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },

    resetAdd() {
      this.addArr = [];
    },
    showUploadDialog() {
      this.dialogAddFile = true;
    },
    getFile(event) {
      var file = event.target.files;
      for (var i = 0; i < file.length; i++) {
        //    上传类型判断
        var imgName = file[i].name;
        var idx = imgName.lastIndexOf(".");
        if (idx != -1) {
          var ext = imgName.substr(idx + 1).toUpperCase();
          ext = ext.toLowerCase();
          if (ext != "xlsx") {
            this.$message({
              type: "error",
              message: "请选择要上传的XLSX文件",
            });
          } else {
            this.addArr.push(file[i]);
          }
        } else {
        }
      }
    },

    submitAddFile() {
      if (0 == this.addArr.length) {
        this.$message({
          type: "info",
          message: "请选择要上传的文件",
        });
        return;
      }

      var formData = new FormData();
      formData.append("num", this.addType);
      formData.append("linkId", this.addId);
      formData.append("rfilename", this.addFileName);
      /**
       * 设置为教师类型
       */
      formData.append("type", 2);
      for (var i = 0; i < this.addArr.length; i++) {
        formData.append("file", this.addArr[i]);
      }
      // let config = {
      //   headers: {
      //     'Content-Type': 'multipart/form-data',
      //     'Authorization': this.token
      //   }
      // };

      stuApi.addStudentExcel(formData).then((response) => {
        console.log(response.success);
        if (response.success) {
          this.$message({
            message: "上传成功",
            type: "success",
          });
          this.dialogAddFile = false;
        }
      });
    },

    //获取教师列表
    getList(page = 1) {
      this.page = page;
      this.role = this.roles[0];
      if (this.role == "学校管理员") {
        this.userQuery.associationName = this.name;
        console.log(this.name);
      }
      teachApi.getTeacherList(this.page, this.limit, this.userQuery).then((response) => {
        //请求成功
        //response接口返回的数据
        this.list = response.data.teachers;
        this.total = response.data.total;
      });
    },
    //清空
    resetData() {
      //表单输入项数据清空
      this.userQuery = {};
      //查询所有讲师数据
      this.getList();
    },
    //获取没有教师的学生列表
    //id => 当前教师id
    getNoTeachStuList(id) {
      this.teacherId = id
      this.stuPage = 1;
      this.dialogTableVisible = true;
      stuApi.getStuNoTeaList(this.stuPage, this.limit).then((response) => {
        this.stuList = response.data.students;
        this.stuTotal = response.data.total;
      });
    },

    //添加学生
    //通过tid， sid
    addStu(id) {
      //todo => 提示框 确定后添加
      teachApi.addTeachStu(this.teacherId, id).then((response) => {
        //提示信息
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //再次渲染
        this.getNoTeachStuList();
      });
    },

    //管理学生
    //通过tid，获取对应的学生
    getStuList(tid) {
      this.teacherId = tid;
      this.hasTeachStatus = true;
      teachApi.getStudentListByTid(tid).then((response) => {
        this.stuList = response.data.students;
        this.stuTotal = response.data.total;
      });
    },

    //移除学生
    //通过sid, 进行移除
    deleteStu(sid) {
      teachApi.deleteStuTeach(sid).then((response) => {
        //提示信息
        this.$message({
          type: "success",
          message: "移除成功!",
        });
        //再次渲染
        this.getStuList(this.teacherId);
      });
    },

    //逻辑删除教师
    deleteTeachByTid(tid) {
      teachApi.deleteTeacher(tid).then((response) => {
        //提示信息
        this.$message({
          type: "success",
          message: "移除成功!",
        });
        //再次渲染
        this.getList();
      });
    },
  },
};
</script>

<style></style>
